//
//  RefreshControl.m
//  Tools
//
//  Created by han on 2019/1/22.
//  Copyright © 2019 han. All rights reserved.
//

#import "RefreshControl.h"

#define kTotalViewHeight    400

@interface RefreshControl()

// 刷新状态
@property (nonatomic, readwrite) BOOL refreshing;
// 是否忽略Inset
@property (nonatomic, readwrite) BOOL ignoreInset;

@property (nonatomic, assign) UIScrollView *scrollView;
@property (nonatomic, assign) UIEdgeInsets originalContentInset;
@property (nonatomic, strong) UIView *activityView;
@end
@implementation RefreshControl

- (instancetype)initInScrollView:(UIScrollView *)scrollView {
    self = [super initWithFrame:CGRectMake(0, -(kTotalViewHeight + self.scrollView.contentInset.top), self.scrollView.frame.size.width, kTotalViewHeight)];
    if (self) {
        self.scrollView = scrollView;
        self.originalContentInset = scrollView.contentInset;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [scrollView addSubview:self];
        [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
        [self.scrollView addObserver:self forKeyPath:@"contentInset" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
        [self setupSubviews];
    }
    return self;
}
- (void)setupSubviews {
    self.activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.activityView.center = CGPointMake(floor(self.frame.size.width / 2), floor(self.frame.size.height / 2));
    self.activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    self.activityView.alpha = 0;
    if ([self.activityView respondsToSelector:@selector(startAnimating)]) {
        [(UIActivityIndicatorView *)self.activityView startAnimating];
    }
    [self addSubview:self.activityView];
    self.refreshing = NO;
}

- (void)dealloc {
    [self.scrollView removeObserver:self forKeyPath:@"contentOffset"];
    [self.scrollView removeObserver:self forKeyPath:@"contentInset"];
    self.scrollView = nil;
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentInset"]) {
        if (!self.ignoreInset) {
            self.originalContentInset = [[change objectForKey:@"new"] UIEdgeInsetsValue];
            self.frame = CGRectMake(0, -(kTotalViewHeight + self.scrollView.contentInset.top), self.scrollView.frame.size.width, kTotalViewHeight);
        }
        return;
    }
    
}

@end
